您可以使用 npm script pre hooks 获得这样的结果。
假设你的启动脚本被称为 "start" ,在你的 package.json 添加
名为“prestart”的脚本,您要在其中运行执行文件下载的脚本。当你调用npm run start时,in 会自动运行
例如:
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"prestart": "node pre-start.js"
},
"author": "",
"license": "ISC"
}
index.js:
const value = require('./new-file.json');
console.log(value);
pre-start.js:
const fs = require('fs');
setTimeout(function() {
const value = {
"one" : 1,
"two" : 2
};
fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)
这里是文章的链接,其中包含更多详细信息:
http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html
另一种方法是在文件写入后运行您的其他代码:
let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
function(response) {
response.pipe(file);
file.on('finish',function(){
// run your code here
}
});